require('../db');
const { UserModel } = require('../db/model');
const { query, execute } = require('../db/connection/mysql');
const handleRequestPayload = require('../utils/handleRequestPayload');

const UserService_mongodb = {
	getUser: () => {
		return UserModel.find();
	},
	addUser: (data) => {
		return UserModel.create(data);
	},
	updateUser: (id, data) => {
		return UserModel.findByIdAndUpdate(id, data);
	},
	delUser: (id) => {
		return UserModel.findByIdAndDelete(id);
	},
};

const UserService_mysql = {
	getUserInfo: async (data) => {
		const { sqlParams, valueList } = handleRequestPayload.query(data);
		const sql = `SELECT * FROM students WHERE ${sqlParams}`;
		return await query(sql, valueList);
	},
	/**
	 * 获取指定数据表的数据总数
	 * @param {Object} data 请求参数
	 * @returns {Promise<{data: any, fields: string[], message: string, error: boolean}>} result - 数据对象
	 *   - data: 响应数据
	 *   - fields: 数据表字段名数组
	 *   - message: 响应消息
	 *   - error: 是否报错
	 */
	getUserList: async (data) => {
		const { current, size, ...filters } = data;
		const { sqlParams, valueList } = handleRequestPayload.query(filters);

		const offset = (current - 1) * size;
		const sql = `SELECT * FROM students WHERE ${sqlParams} LIMIT ? OFFSET ?`;

		valueList.push(size, offset);

		return await query(sql, valueList);
	},
	addUser: async (data) => {
		const { props, labels, values } = insertPayload(data);

		const sql = `insert into students(${props}) values(${labels})`;
		const res = await query(sql, values);
		return res.error ? new Error(res.error) : null;
	},
	updateUser: async (id, data) => {
		const { props, values } = updatePayload(data);

		const sql = `update students set ${props} where id = ?`;
		const payload = values.concat(id);
		const res = await query(sql, payload);
		return res.error ? new Error(res.error) : null;
	},
	delUser: async (id) => {
		const findUser = await UserService_mysql.getUserInfo({ id });
		if (!findUser || findUser.length === 0) {
			return new Error('此用户不存在');
		}
		const sql = 'delete from students where id = ?';
		const res = await query(sql, [id]);
		return res.error ? new Error(res.error) : null;
	},
};

switch (process.env.NODE_ENV_DB_TYPE) {
	case 'mysql':
		module.exports = UserService_mysql;
		break;
	case 'mongodb':
		module.exports = UserService_mongodb;
		break;
	default:
		module.exports = UserService_mongodb;
}
